package com.xiangjun.proxytest.cglibdynamicproxytest;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyFactory {
    public Object getProxy(Object targetObject){
        Enhancer enhancer = new Enhancer();

        //Cglib通过继承被代理的类来实现代理，所以这里需要把被代理类作为代理类的父类传入
        enhancer.setSuperclass(targetObject.getClass());

        MethodInterceptor interceptor = new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("\n调用前加密\n");
                Object res = methodProxy.invokeSuper(o,objects);
                System.out.println("\n调用后加密\n");
                return res;
            }
        };

        enhancer.setCallback(interceptor);

        return enhancer.create();
    }
}
